import torch
from torch import nn


class RNN(nn.Module):
    def __init__(self, vocab_size, hidden_size, num_layers=1, device=None):
        super().__init__()
        self.vocab_size = vocab_size
        self.hidden_size = hidden_size

        self.device = device if device else torch.device("cuda" if torch.cuda.is_available() else "cpu")

        self.rnn = nn.RNN(vocab_size, hidden_size, num_layers, batch_first=True, device=device)  # 时间序的隐藏状态求解
        self.fc = nn.Linear(hidden_size, vocab_size, device=device)  # 隐藏状态预测输出

    def forward(self, x, h):
        x0, h = self.rnn(x, h)
        x0 = x0.reshape(-1, self.hidden_size)
        y = self.fc(x0)
        return y.reshape(x.shape), h
